import SockJS from 'sockjs-client';
import { Client } from '@stomp/stompjs';

class WebSocketService {
    constructor() {
        this.stompClient = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 3;
        this.reconnectDelay = 5000;
        this.messageQueue = [];
        this.messageHandlers = new Set();
        this.isConnecting = false;
    }

    connect() {
        if (this.isConnecting) {
            console.log('WebSocket正在连接中，请稍候...');
            return;
        }

        this.isConnecting = true;
        const wsUrl = `${import.meta.env.VITE_WS_URL || 'http://localhost:8080'}/api/ws`;
        console.log('正在连接WebSocket服务器:', wsUrl);

        const sockjs = new SockJS(wsUrl, null, {
            transports: ['websocket', 'xhr-streaming', 'xhr-polling'],
            timeout: 5000
        });

        sockjs.onopen = () => {
            console.log('SockJS连接已建立');
        };

        sockjs.onclose = (event) => {
            console.log('SockJS连接已关闭:', event);
            this.isConnecting = false;
        };

        sockjs.onerror = (error) => {
            console.error('SockJS错误:', error);
            this.isConnecting = false;
        };

        this.stompClient = new Client({
            webSocketFactory: () => sockjs,
            debug: (str) => {
                if (str.includes('error') || str.includes('Error') || str.includes('failed')) {
                    console.error('STOMP错误:', str);
                } else {
                    console.log('STOMP:', str);
                }
            },
            reconnectDelay: this.reconnectDelay,
            heartbeatIncoming: 4000,
            heartbeatOutgoing: 4000,
            onConnect: () => {
                console.log('STOMP连接成功');
                this.reconnectAttempts = 0;
                this.isConnecting = false;
                this.processMessageQueue();
                
                // 连接成功后立即订阅消息
                this.stompClient.subscribe('/topic/chat', (message) => {
                    try {
                        const data = JSON.parse(message.body);
                        console.log('收到消息:', data);
                        this.messageHandlers.forEach(handler => {
                            if (typeof handler === 'function') {
                                handler(data);
                            }
                        });
                    } catch (error) {
                        console.error('处理消息时出错:', error);
                    }
                });
            },
            onStompError: (frame) => {
                console.error('STOMP协议错误:', frame.headers.message || '未知错误');
                this.isConnecting = false;
            },
            onWebSocketClose: () => {
                console.log('WebSocket连接已关闭');
                this.isConnecting = false;
                this.handleReconnect();
            },
            onWebSocketError: (event) => {
                console.error('WebSocket连接错误:', event);
                this.isConnecting = false;
            }
        });

        this.stompClient.activate();
    }

    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`正在尝试重新连接 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            setTimeout(() => {
                if (!this.isConnecting) {
                    this.connect();
                }
            }, this.reconnectDelay);
        } else {
            console.error('达到最大重连次数，连接失败');
            this.messageHandlers.forEach(handler => {
                if (typeof handler === 'function') {
                    handler({
                        type: 'connection_status',
                        content: 'disconnected',
                        timestamp: Date.now()
                    });
                }
            });
        }
    }

    send(message) {
        if (this.stompClient && this.stompClient.connected) {
            this.stompClient.publish({
                destination: '/app/chat',
                body: JSON.stringify(message)
            });
        } else {
            console.error('WebSocket未连接，消息已加入队列');
            this.messageQueue.push(message);
        }
    }

    processMessageQueue() {
        while (this.messageQueue.length > 0) {
            const message = this.messageQueue.shift();
            this.send(message);
        }
    }

    addMessageHandler(handler) {
        console.log('添加消息处理器');
        this.messageHandlers.add(handler);
    }

    removeMessageHandler(handler) {
        console.log('移除消息处理器');
        this.messageHandlers.delete(handler);
    }

    disconnect() {
        if (this.stompClient) {
            this.stompClient.deactivate();
            this.isConnecting = false;
            this.reconnectAttempts = 0;
        }
    }
}

export const websocketService = new WebSocketService();
export default websocketService;